<template>
  <div class="all">
    <!-- 顶部 -->
    <!-- 搜索框 -->
    <div class="top"></div>
    <!-- 中间的表格 -->
    <div class="middle">
      <el-table
        :data="tableData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        :header-cell-style="{
          background: 'rgba(61,157,255,0.05)',
          color: '#333333',
        }"
      >
        <el-table-column prop="taskName" label="作业名称" align="center">
        </el-table-column>
        <el-table-column prop="cover" label="封面图" align="center">
          <template slot-scope="scope">
            <img
              :src="$store.state.user.BASE_URL + scope.row.cover"
              alt=""
              style="width: 70px; height: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="source" label="作业来源" align="center">
          <template slot-scope="scope">
            {{ getSource(scope.row.source) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="发布" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status == 1"
              type="success"
              size="small"
              plain
              @click="showAdd($event, scope.row.taskId)"
              >发布</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="eiooe" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              plain
              type="primary"
              size="small"
              @click="gradeEdit($event, scope.row.taskId)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 下面的分页器 -->
    <div>
      <pagination-page @size="changeSize" @page="changePage" :total="total" />
    </div>
    <!-- 遮罩层 -->
    <el-dialog
      title="学习作业列表"
      :visible.sync="dialogVisible"
      width="800px"
      v-if="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form ref="ruleForm" :model="form" label-width="80px" :rules="rules">
        <!-- 作业名称 -->
        <div class="box">
          <el-row>
            <el-col :span="12">
              <el-form-item label="作业名称" prop="taskName">
                <el-input
                  :disabled="forbiddenshow"
                  v-model="form.taskName"
                  placeholder="请输入作业名称"
                  style="width: 90%"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="适合人群" prop="gradeId">
                <!-- <el-select
                  :disabled="forbiddenshow"
                  clearable
                  v-model="form.gradeId"
                  placeholder="班级"
                  style="width: 47%"
                >
                  <el-option
                    v-for="(item, index) in gradeSource"
                    :value="item.gradeId"
                    :label="item.gradeName"
                    :key="index"
                  ></el-option>
                </el-select> -->
                <el-input
                  :disabled="forbiddenshow"
                  v-model="form.gradeName"
                  placeholder="请输入适合人群"
                  style="width: 47%"
                ></el-input>
                <el-select
                  :disabled="forbiddenshow"
                  v-model="form.sex"
                  placeholder="性别"
                  style="width: 47%"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="topp">
          <el-row>
            <el-col :span="12">
              <el-form-item label="上传图片" prop="cover">
                <el-upload
                  style="width: 300px"
                  class="upload-demo"
                  drag
                  v-if="!form.cover"
                  :on-success="picUpload"
                  :before-upload="beforeUpload"
                  :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
                  multiple
                  :headers="{
                    'access-token': $store.state.user.TOKEN,
                  }"
                >
                  <div v-if="!form.cover">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">
                      将文件拖到此处，或<em>点击上传</em>
                    </div>
                  </div>

                  <div class="el-upload__tip" slot="tip">
                    只能上传jpg/png文件，建议不超过500kb
                  </div>
                </el-upload>
                <img
                  style="
                    width: auto;
                    height: auto;
                    max-height: 100%;
                    max-width: 100%;
                  "
                  v-if="form.cover"
                  :src="$store.state.user.BASE_URL + form.cover"
                  alt=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="简介" prop="tips">
                <el-input
                  style="with: 210px"
                  :disabled="forbiddenshow"
                  type="textarea"
                  v-model="form.tips"
                  :autosize="{ minRows: 6.5, maxRows: 6.5 }"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 视频 -->
        <el-form-item label="上传视频" prop="video" style="width: 70%">
          <el-upload
            class="avatar-uploader"
            :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
            v-bind:on-progress="uploadVideoProcess"
            v-bind:on-success="handleVideoSuccess"
            v-bind:before-upload="beforeUploadVideo"
            v-bind:show-file-list="false"
            :headers="{
              'access-token': $store.state.user.TOKEN,
            }"
          >
            <video
              v-if="form.video != '' && !videoFlag"
              v-bind:src="$store.state.user.BASE_URL + form.video"
              class="avatar video-avatar"
              controls="controls"
            >
              您的浏览器不支持视频播放
            </video>
            <i
              v-else-if="form.video == '' && !videoFlag"
              class="el-icon-plus avatar-uploader-icon"
            ></i>
            <el-progress
              v-if="videoFlag == true"
              type="circle"
              v-bind:percentage="videoUploadPercent"
              style="margin-top: 7px"
            ></el-progress>
          </el-upload>
          <p class="Upload_pictures">
            <span></span>
            <span class="stp"
              >最多可以上传1个视频，建议大小50M，推荐格式mp4</span
            >
          </p>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="footerShow">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<style>
.el-table .warning-row {
  background: #ebf5ff;
}

.el-table .success-row {
  background: #f5faff;
}
</style>

<script>
import {
  // 学习作业列表
  getworklist,
  // 发布学习作业
  getreleaselearning,
} from "@/api/worklist/index";
import { gradeList } from "@/api/school/grade";
//  上传学习作业列表详情
import { getjobdetails } from "@/api/uploadand/index.js";
export default {
  data() {
    return {
      options: [
        {
          value: "3",
          label: "全性别",
        },
        {
          value: "2",
          label: "女",

          disabled: true,
        },
        {
          value: "1",
          label: "男",
          disabled: true,
        },
      ],
      forbiddenshow: false,
      footerShow: true,
      videoFlag: false,
      //是否显示进度条
      videoUploadPercent: "",
      //进度条的进度，
      isShowUploadVideo: false,

      dialogVisible: false,

      video: "",
      input2: "",
      total: -1,
      page: {
        pageSize: 10,
        pageNum: 1,
      },
      tableData: [],
      gradeSource: [],
      form: {
        gradeName: "",
        taskName: "",
        gradeId: "",
        sex: "",
        cover: "",
        video: "",
        tips: "",
        taskId: "",
      },
      rules: {
        // 作业名称
        taskName: [
          {
            required: true,
            message: "请输入作业名称",
            trigger: "blur",
          },
        ],
        // 适合班级
        gradeId: [
          {
            required: true,
            message: "请输入班级",
            trigger: "blur",
          },
        ],
        // 简介
        tips: [
          {
            required: true,
            message: "请输入简介",
            trigger: "blur",
          },
        ],
        //  图片
        cover: [
          {
            required: true,
            message: "请输入简介",
            trigger: "blur",
          },
        ],
        // 视频
        video: [
          {
            required: true,
            message: "请输入简介",
            trigger: "blur",
          },
        ],
      },
    };
  },

  created() {
    this.getworklists();
    this.getGradeLists();
  },
  methods: {
    gradeEdit(evt, val, level) {
      let target = evt.target;
      if (target.nodeName == "SPAN") {
        target = evt.target.parentNode;
      }
      target.blur();
      let obj = {
        taskId: val,
      };
      getjobdetails(obj).then((res) => {
        if (!level) {
          this.footerShow = false;
          this.forbiddenshow = true;
        } else {
        }
        this.form = { ...res.result };
        this.dialogVisible = true;
      });
    },
    getSource(val) {
      if (val == 0) {
        return "平台";
      } else if (val == 1) {
        return "区域";
      } else if (val == 2) {
        return "校";
      } else if (val == 3) {
        return "教师";
      }
    },
    //  照片上传
    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = ["jpeg", "jpg", "png"];
      if (!types.includes(fileSuffix)) {
        this.$message.error(`文件只能是 ${types.join()} 格式!`);
      }
      return types.includes(fileSuffix);
    },
    // 上传图片成功的函数
    picUpload(e, file) {
      if (e.code === 200) {
        this.form.cover = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
      this.$refs.ruleForm.validate(() => {});
      this.loading = false;
    },
    // 视频上传
    beforeUploadVideo(file) {
      var fileSize = file.size / 1024 / 1024 < 50; //控制大小  修改50的值即可
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb",
          "video/mov",
        ].indexOf(file.type) == -1 //控制格式
      ) {
        layer.msg("请上传正确的视频格式");
        return false;
      }
      if (!fileSize) {
        layer.msg("视频大小不能超过50MB");
        return false;
      }
      this.isShowUploadVideo = false;
    },
    //进度条
    uploadVideoProcess(event, file, fileList) {
      //注意在data中添加对应的变量名
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },
    //上传成功回调

    handleVideoSuccess(res, file) {
      this.isShowUploadVideo = true;
      this.videoFlag = false;
      this.videoUploadPercent = 0;

      //后台上传数据
      if (res.code == 200) {
        this.form.video = res.result.pic; //上传成功后端返回视频地址 回显
      } else {
        this.$message.error("上传失败！");
      }
    },

    // 获取学习作业数据
    getworklists() {
      let data = {
        userId: this.$store.state.user.USER_INFO.id,
        ...this.page,
      };
      getworklist(data).then((res) => {
        if (res.code == 200) {
          this.tableData = res.result;
          this.total = res.total;
        }
      });
    },
    // 年级
    getGradeLists() {
      gradeList({ schoolId: this.$store.state.user.USER_INFO.pscShId }).then(
        (response) => {
          if (response.code === 200) {
            this.gradeSource = response.result;
          }
        }
      );
    },

    //确定保存
    showAdd(evt, val) {
      let target = evt.target;
      let data = {
        taskId: val,
      };
      getreleaselearning(data).then((res) => {
        if (res.code == 200) {
          this.dialogFormVisible = false;
          this.$message.success("发布成功!");

          this.getworklists();
        } else {
          this.$message.error(res.message);
        }
      });
      if (target.nodeName == "SPAN") {
        target = evt.target.parentNode;
      }
      target.blur();
    },

    // 分页器
    changeSize(size) {
      this.page.pageSize = size;
      this.getworklists();
    },
    changePage(page) {
      this.page.pageNum = page;
      this.getworklists();
    },

    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 2) {
        return "warning-row";
      } else if (rowIndex === 4) {
        return "success-row";
      }
      return "";
    },
  },
};
</script>

<style scoped lang="scss">
.top {
  display: flex;
  justify-content: end;
  padding: 5px;
  box-sizing: border-box;
}

.el-pagination {
  display: flex;
  justify-content: flex-end;
}
.box {
  display: flex;
  justify-content: space-between;
}
.imgs {
  width: 250px;
  height: 130px;
}
.imgss {
  width: 50px;
  height: 30px;
}
.topp {
  display: flex;
  justify-content: space-between;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9 !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px !important;
  position: relative !important;
  overflow: hidden !important;
}
.avatar-uploader .el-upload:hover {
  border: 1px dashed #d9d9d9 !important;
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 360px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 248px;
  height: 178px;
  display: block;
}
::v-deep .el-textarea {
  width: 246px;
}
::v-deep .el-upload-dragger {
  width: 248px;
  height: 150px;
}
::v-deep .el-dialog__body {
  padding: 15px 48px;
}
::v-deep .el-dialog {
  margin-top: 7vh !important;
}
.stp {
  font-size: 12px;
}
</style>
